<script setup lang="ts">
import axios from "axios";
import { ElMessage } from "element-plus";
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import { router } from "../../router";
import type { Book, Category, CategoryWithBooksVO } from "../../types/Book";
import type { ResultContext } from "../../types/ResultContext";

const props = defineProps<{
  category?: Category;
}>();

const bookList = ref<Book[]>([]);
const page = ref(1);
const size = 20; // 每页显示的图书数量
const hasMore = ref(true);

watch(
  () => props.category,
  async newCategory => {
    // 重置分页参数和状态
    page.value = 1;
    hasMore.value = true;
    bookList.value = [];

    try {
      let res;
      if (!newCategory?.id) {
        // 全部书籍
        res = await axios.get<ResultContext<CategoryWithBooksVO>>(
          `http://localhost:8080/api/categories/books`,
          { params: { page: page.value, size } },
        );
        bookList.value = res.data.data.books;
      } else {
        // 分类下的书籍
        res = await axios.get<ResultContext<CategoryWithBooksVO>>(
          `http://localhost:8080/api/categories/${newCategory.id}`,
          { params: { page: page.value, size } },
        );
        bookList.value = res.data.data.books;
      }
      if (bookList.value.length < size) {
        hasMore.value = false;
      }
    } catch (_error) {
      ElMessage.error("获取图书失败。");
    }
  },
  { immediate: true },
);

const loadMore = async () => {
  if (!hasMore.value) return;

  page.value++;
  try {
    let res;
    if (!props.category?.id) {
      // 全部书籍
      res = await axios.get<ResultContext<CategoryWithBooksVO>>(
        `http://localhost:8080/api/categories/books`,
        { params: { page: page.value, size } },
      );
      bookList.value.push(...res.data.data.books);
      if (res.data.data.books.length < size) {
        hasMore.value = false;
      }
    } else {
      // 分类下的书籍
      res = await axios.get<ResultContext<CategoryWithBooksVO>>(
        `http://localhost:8080/api/categories/${props.category.id}`,
        { params: { page: page.value, size } },
      );
      bookList.value.push(...res.data.data.books);
      if (res.data.data.books.length < size) {
        hasMore.value = false;
      }
    }
  } catch (_error) {
    ElMessage.error("图书加载失败。");
    page.value--; // 加载失败回退页码
  }
};

const onScroll = () => {
  const scrollTop = window.scrollY || window.pageYOffset;
  const viewportHeight = window.innerHeight;
  const fullHeight = document.documentElement.scrollHeight;

  if (scrollTop + viewportHeight >= fullHeight - 100) {
    void loadMore();
  }
};

onMounted(() => {
  window.addEventListener("scroll", onScroll);
});

onBeforeUnmount(() => {
  window.removeEventListener("scroll", onScroll);
});
</script>

<template>
  <div class="category-content">
    <div class="content-header">
      <h2 class="category-title">
        {{ props.category?.name || "全部书籍" }}
      </h2>
      <p class="category-desc">探索这个分类下的精彩图书</p>
    </div>

    <div class="content-body">
      <div class="book-grid" v-if="bookList.length > 0">
        <div
          v-for="book in bookList"
          :key="book.id"
          class="book-card"
          @click="router.push(`/details/${book.id}`)"
        >
          <div class="book-cover-wrapper">
            <img
              :src="`/img/${book.img}`"
              alt="本书版权所有，侵权必究"
              class="book-cover"
            />
          </div>
          <div class="book-info">
            <h3 class="book-title">{{ book.title }}</h3>
            <p class="book-author">{{ book.author }}</p>
            <p class="book-description">{{ book.description }}</p>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-else-if="!hasMore">
        <div class="empty-icon">📚</div>
        <h3>暂无图书</h3>
        <p>这个分类下还没有图书，请稍后再来查看</p>
      </div>

      <!-- 加载更多提示 -->
      <div class="load-more" v-if="hasMore">
        <div class="loading-indicator">
          <div class="loading-spinner"></div>
          <span>加载更多图书...</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.category-content {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.content-header {
  text-align: center;
  margin-bottom: 32px;
  padding: 32px 0;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 16px;
}

.category-title {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #333;
}

.category-desc {
  margin: 0;
  font-size: 16px;
  color: #666;
}

.content-body {
  position: relative;
}

.book-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.book-card {
  background: #fff;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
}

.book-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.book-cover-wrapper {
  position: relative;
  aspect-ratio: 3/4;
  overflow: hidden;
}

.book-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.book-card:hover .book-cover {
  transform: scale(1.05);
}

.book-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.book-card:hover .book-overlay {
  opacity: 1;
}

.book-actions {
  display: flex;
  gap: 12px;
}

.action-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.action-btn.primary {
  background: #409eff;
  color: white;
}

.action-btn.primary:hover {
  background: #53c0ff;
  transform: translateY(-1px);
}

.action-btn.secondary {
  background: rgba(255, 255, 255, 0.9);
  color: #333;
}

.action-btn.secondary:hover {
  background: white;
  transform: translateY(-1px);
}

.book-info {
  padding: 16px;
}

.book-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-clamp: 2;
  overflow: hidden;
}

.book-author {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.book-description {
  margin: 0;
  font-size: 13px;
  color: #888;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-clamp: 2;
  overflow: hidden;
}

.empty-state {
  text-align: center;
  padding: 64px 32px;
  color: #666;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-state h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  color: #333;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}

.load-more {
  display: flex;
  justify-content: center;
  padding: 32px 0;
}

.loading-indicator {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #666;
  font-size: 14px;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #f0f0f0;
  border-top: 2px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .category-content {
    padding: 16px;
  }

  .book-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 16px;
  }

  .content-header {
    padding: 24px 16px;
    margin-bottom: 24px;
  }

  .category-title {
    font-size: 24px;
  }

  .category-desc {
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .book-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 12px;
  }

  .book-actions {
    flex-direction: column;
    gap: 8px;
  }

  .action-btn {
    padding: 6px 12px;
    font-size: 12px;
  }
}
</style>
